package com.jw.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jw.system.entity.Customer;
import com.jw.system.entity.Dept;
import com.jw.system.entity.User;
import com.jw.system.entity.vo.DepartmentVO;
import com.jw.system.entity.vo.UserVO;
import com.jw.system.mapper.DeptMapper;
import com.jw.system.mapper.RoleMapper;
import com.jw.system.mapper.UserMapper;
import com.jw.system.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author jw
 * @since 2021-04-20
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<DepartmentVO> findAllVO() {
        List<Dept> departments = deptMapper.selectList(null);
        //转vo
        List<DepartmentVO> departmentVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(departments)) {
            for (Dept department : departments) {
                DepartmentVO d = new DepartmentVO();
                BeanUtils.copyProperties(department, d);
                QueryWrapper<User> queryWrapper=new QueryWrapper();
                queryWrapper.eq("dept_id",department.getId());
                d.setTotal(userMapper.selectCount(queryWrapper));
                departmentVOS.add(d);
            }
        }
        return departmentVOS;
    }

    @Override
    public Page<DepartmentVO> getDeptList(Integer current, Integer size, DepartmentVO dept) {
        Page<Dept> page = new Page<>(current, size);
        QueryWrapper<Dept> queryWrapper = new QueryWrapper();
        if (dept.getName() != null && !"".equals(dept.getName())) {
            queryWrapper.like("name", dept.getName());
        }
        //获得部门实体类分页结果
        Page<Dept> deptPage = deptMapper.selectPage(page,queryWrapper);
        List<DepartmentVO> departmentVOS  = new ArrayList<>();
        //转为vo
        for(Dept dept1:deptPage.getRecords()){
            DepartmentVO d = new DepartmentVO();
            BeanUtils.copyProperties(dept1, d);
            QueryWrapper<User> queryWrapper2=new QueryWrapper();
            queryWrapper2.eq("dept_id",dept1.getId());
            d.setTotal(userMapper.selectCount(queryWrapper2));
            departmentVOS.add(d);
        }
        Page<DepartmentVO> dVOPage = new Page<>();
        dVOPage.setRecords(departmentVOS);
        dVOPage.setTotal(deptPage.getTotal());
        return dVOPage;
    }

}
